package recommendation;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class MovieSimilar {
	private static MovieSimilar instance = new MovieSimilar();
	private String filename="recommender_system_data\\simtable";
	private HashMap<String,ArrayList<MovieSimilar_Value>> moviesimilar = new HashMap<String,ArrayList<MovieSimilar_Value>>();
	private MovieSimilar() {
		try {
			String content = null;
			FileReader file=new FileReader(filename);
			while((content = getOne(file))!=null) {
				String []sp = content.split(",");
				String []sp2 = sp[1].split(":");
				double value = Double.parseDouble(sp2[1]);
				if(sp[0].equals(sp2[0])) {//id相同忽略
					continue;
				}
				MovieSimilar_Value mv = new MovieSimilar_Value(sp2[0],value);
				if(moviesimilar.containsKey(sp[0])) {
					ArrayList<MovieSimilar_Value> list=moviesimilar.get(sp[0]);
					list.add(mv);
					if(list.size()>Source.RECOMMENDEDCOUNT)
					{
						Collections.sort(list,new ArraySort());
						list.remove(list.size()-1);
					}			
				}else {
					ArrayList<MovieSimilar_Value> list=new ArrayList<MovieSimilar_Value>();
					list.add(mv);
					moviesimilar.put(sp[0], list);
				}
				
				mv = new MovieSimilar_Value(sp[0],value);
				if(moviesimilar.containsKey(sp2[0])) {
					ArrayList<MovieSimilar_Value> list=moviesimilar.get(sp2[0]);
					list.add(mv);
					if(list.size()>Source.RECOMMENDEDCOUNT)
					{
						Collections.sort(list,new ArraySort());
						list.remove(list.size()-1);
					}	
				}else {
					ArrayList<MovieSimilar_Value> list=new ArrayList<MovieSimilar_Value>();
					list.add(mv);
					moviesimilar.put(sp2[0], list);
				}
			}
			file.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.print(filename+".文件不存在");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static MovieSimilar getInstance() {
		return instance;
	}
	public String getOne(FileReader file) {//获取simtable每一条数据
		String content=new String();
		int c;
		try {
			while((c=file.read())!='\t' &&c>=0) {
				content += (char)c;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(content.length()<=0)
			return null;
		return content;
	}
	public ArrayList<MovieSimilar_Value> getMovieList(String id){
		ArrayList<MovieSimilar_Value> result;
		if(moviesimilar.containsKey(id))
			result = moviesimilar.get(id);
		else
			result = null;
		return result;
		
	}
}
